<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace model;

/**
 * Description of TblProduct
 *
 * @author Damian
 */
class TblProduct extends Model {

    /**
     *
     * @readwrite
     */
    public $DefaultPicture;

    /**
     * @readwrite
     * @column
     * @primary
     * @type int
     * @length 11
     * 
     */
    public $ProductID;

    const ID = "ProductID";

    /**
     * @readwrite
     * @column
     * @type varchar
     * @lenght 50
     * @validate max(50), required, alphanumeric
     */
    public $Name;

    const NAME = "Name";

    /**
     * <p>cena brutto</p>
     * @readwrite
     * @column
     * @type decimal
     * @validate numeric, minValue(0), required
     */
    public $GrossPrice;

    const GROSS_PRICE = "GrossPrice";

    /**
     * <p>cena netto</p>
     * @readwrite
     * @column
     * @type decimal
     * @validate numeric, minValue(0), required
     */
    public $NetPrice;

    const NET_PRICE = "NetPrice";

    /**
     * <p>vat</p>
     * @readwrite
     * @column
     * @type int
     * @validate numeric
     */
    public $VAT;

    const VAT = "VAT";

    /**
     * @readwrite
     */
    public $Active;

    const ACTIVE = "Active";

    /**
     * @readwrite
     * @column 
     * @type int
     * @length 11
     * @validate numeric, required
     */
    public $Amount;

    const AMOUNT = "Amount";

    /**
     * @readwrite
     * @column
     * @type varchar
     * @lenght 250
     * @validate max(250), required, alphanumeric
     */
    public $ShortDescription;

    const SHORT_DESCRIPTION = "ShortDescription";

    /**
     * @readwrite
     * @column
     * @type text
     * @lenght 500
     * @validate max(5000), required, alphanumeric
     */
    public $Description;

    const DESCRIPTION = "Description";

    /**
     * @readwrite
     */
    public $Visable;

    const VISABLE = "Visable";

    /**
     * @readwrite
     */
    public $OldPrice;

    const OLD_PRICE = "OldPrice";

    /**
     * @readwrite
     */
    public $CategoryID;

    const CATEGORY_ID = "CategoryID";

    /**
     * @readwrite
     */
    public $ShopID;

    const SHOP_ID = "ShopID";

    /**
     * @readwrite
     */
    public $ManufacturerID;

    const MANUFACTURER_ID = "ManufacturerID";

    /**
     * @readwrite
     */
    public $CurrencyID;

    const CURRENCY_ID = "CurrencyID";

    /**
     *
     * @readwrite
     */
    public $URL;

    const URL = "URL";

    /**
     * @readwrite
     * @column 
     * @type decimal
     * @length 11
     */
    public $AvgMark;
    const AVG_MARK = "AvgMark";
    
    /**
     * @readwrite
     */
    public $AdditionDate;
    const ADDITION_DATE="AdditionDate";

    private function generateURL() {
        $this->URL = str_replace([" ","ą","ć","ę","ń","ś","ł","ó","ż","ź"], [" ","a","c","e","n","s","l","o","z","z"], strtolower(strip_tags($this->Name)));
    }

    /**
     * <p>sprawdza czy dany element jest w danym sklepie</p>
     * @param \model\TblShop $shop <p>sklep do sprawdzenia</p>
     * @return boolean
     */
    public function compare(TblShop &$shop) {
        $myshop = TblShop::getModel()->getByPrimaryKey($this->ShopID);
        if (!$myshop) {
            return false;
        }
        return $myshop->ShopID == $shop->ShopID;
    }

    public function validate() {
        if (parent::validate()) {
            $shop = TblShop::getModel()->getByPrimaryKey($this->ShopID);
            $manufacturer = TblManufacturer::getModel()->getByPrimaryKey($this->ManufacturerID);
            $error = false;
            if (!$shop) {
                $error = true;
            }
            if (!$manufacturer || !$manufacturer->compare($shop)) {
                $this->errors["ManufacturerID"][] = "wybrany producent nie istnieje";
                $error = true;
            }
            $category = TblCategory::getModel()->getByPrimaryKey($this->CategoryID);
            if (!$category || !$category->compare($shop)) {
                $this->errors["CategoryID"][] = "wybrana kategoria nie istnieje";
                $error = true;
            }
            if (!in_array($this->VAT, [0, 2, 5, 8, 22, 23])) {
                $error = true;
                $this->errors["VAT"][] = "Nieprawidłowa wartość podatku vat";
            }
            $this->generateURL();
            return !$error;
        }
        return false;
    }

    /**
     * Czyści wszystkie powiązania z innymi tabelami
     */
    public function clearRelations() {
        $deleteFeatures = new \model\Criteria();
        $deleteFeatures->from(\model\TblProductFeature::getModel()->getTable())
                ->where(\model\TblProductFeature::PRODUCT_ID, "=", $this->ProductID);

        $deleteFeatures->delete();
        $deletePictures = new Criteria();
        $deletePictures->from(TblProductPicture::getModel()->getTable())
                ->where(TblProductPicture::PRODUCT_ID, "=", $this->ProductID);
        $deletePictures->delete();

        $relatedCriteria = new Criteria();
        $relatedCriteria->from(TblRelatedProduct::getModel()->getTable())
                ->where(TblRelatedProduct::PRODUCT_1, "=", $this->ProductID)
                ->where(TblRelatedProduct::PRODUCT_2, "=", $this->ProductID, false, " and ");
        $relatedCriteria->delete();
    }

    /**
     * 
     * @return \model\Criteria <p>ogólne kryteria do pobrania produktu</p>
     */
    public function createCriteria($shopID = false) {
        $productsCriteria = new \model\Criteria();
        $productsCriteria->from(\model\TblProduct::getModel()->getTable())
                ->where(\model\TblProduct::VISABLE, "=", 1, false, " ")
                ->join(\model\TblProductPicture::getModel())
                ->join(TblPicture::getModel())
                ->join(\model\TblManufacturer::getModel())
                ->join(\model\TblCategory::getModel())
                ->join(\model\TblCurrency::getModel())               
                ->where(\model\TblProductPicture::DEFAULT_PICTURE, "=", 1, \model\TblProductPicture::getModel()->getTable(), " and ");
        if ($shopID) {
            $productsCriteria->where(\model\TblProduct::SHOP_ID, "=", $shopID, \model\TblProduct::getModel()->getTable(), " and ");
        }
        return $productsCriteria;
    }

    public function getByManufacturer(TblManufacturer $manufacturer, $operator = " and ") {
        // $productsCriteria = $this->createCriteria();
        //  $productsCriteria->where(TblManufacturer::ID, "=", $manufacturer->ManufacturerID,  TblManufacturer::getModel()->getTable(), $operator);
    }
    /**
     * <p>ustawia powiązane tabele</p>
     * @param type $features <p>cechy do ustawienia</p>
     * @param type $related <p>tablica powiązanych produtków</p>
     */
    public function setRelations($features, $related) {
        if (is_array($features)) {
            foreach ($features as $feature) {
                $proFeature = new \model\TblProductFeature([
                    \model\TblProductFeature::VALUE => $feature["value"],
                    \model\TblProductFeature::CATEGORY_FEATURE_ID => $feature["CategoryFeatureID"],
                    \model\TblProductFeature::PRODUCT_ID => $this->ProductID
                ]);
                $proFeature->save();
            }
        }
        if (is_array($related)) {
            foreach ($related as $prod) {
                $relation = new \model\TblRelatedProduct(
                        [
                    \model\TblRelatedProduct::PRODUCT_1 => $this->ProductID,
                    \model\TblRelatedProduct::PRODUCT_2 => $prod[0],
                    \model\TblRelatedProduct::SHOP_ID => $this->ShopID
                ]);
                $relation->save();
            }
        }
    }
    /**
     * <p>ustawia powiązane obrazki</p>
     * @param type $pictures 
     * @param type $mainPicture <p>id głównego obrazka</p>
     */
    public function setRelatedPictures(&$pictures, &$mainPicture) {
        $hasDefault = false;
        if (is_array($pictures)) {
            foreach ($pictures as $picture) {
                $default = (int) ($picture == $mainPicture);
                $ProductPicture = new \model\TblProductPicture([
                    \model\TblProductPicture::PRODUCT_ID => $this->ProductID,
                    \model\TblProductPicture::PICTURE_ID => $picture,
                    \model\TblProductPicture::DEFAULT_PICTURE => $default]);
                $ProductPicture->save();
                if ($default) {
                    $hasDefault = TRUE;
                }
            }
        } else if ($mainPicture || !$hasDefault) {
            $ProductPicture = new \model\TblProductPicture([
                \model\TblProductPicture::PRODUCT_ID => $this->ProductID,
                \model\TblProductPicture::PICTURE_ID => $mainPicture,
                \model\TblProductPicture::DEFAULT_PICTURE => 1]);
            $ProductPicture->save();
        }
    }
    public static function createOrderString($id){
        switch ($id){
            case 1: return [TblProduct::ADDITION_DATE,"desc"];
            case 2: return [TblProduct::ADDITION_DATE,"asc"];
            case 3: return [TblProduct::GROSS_PRICE,"asc"];
            case 4: return [TblProduct::GROSS_PRICE,"desc"];
            case 5: return [TblProduct::AVG_MARK,"asc"];
            case 6: return [TblProduct::AVG_MARK,"desc"];
            case 7: return [TblProduct::AMOUNT,"asc"];
            case 8: return [TblProduct::AMOUNT,"desc"];
            case 9: return [TblProduct::NAME,"asc"];
            case 10: return [TblProduct::NAME,"desc"];
            default :return [TblProduct::ADDITION_DATE,"desc"];
        }
    }

}
